package com.cheyunkeji.er.fragment.evaluate;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.aspsine.swipetoloadlayout.OnLoadMoreListener;
import com.aspsine.swipetoloadlayout.OnRefreshListener;
import com.cheyun.netsalev3.R;
import com.cheyun.netsalev3.widget.MyEditText;
import com.cheyunkeji.er.activity.evaluate.AddCarArchiveActivity;
import com.cheyunkeji.er.adapter.evaluate.CarArchiveAdapter;
import com.cheyunkeji.er.base.BaseFragment;
import com.cheyunkeji.er.bean.evaluate.CarArchive;
import com.cheyunkeji.er.http.ApiClient;
import com.cheyunkeji.er.http.HttpConstants;
import com.cheyunkeji.er.http.RespCallback;
import com.cheyunkeji.er.utils.ChannelInfoUtil;
import com.cheyunkeji.er.view.SToast;
import com.cheyunkeji.er.view.SwipeLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/** Created by Michael on 2017/3/17 16:32. */
public class CarArchiveFragment extends BaseFragment
    implements OnRefreshListener, OnLoadMoreListener, TextWatcher, AdapterView.OnItemClickListener {

  private static final String TAG = CarOwnerArchiveFragment.class.getSimpleName();

  //    每页数据量
  private static final int COUNTS_PER_PAGE = 10;

  //    当前列表状态 STATE_REFRESH : 下拉刷新 ，STATE_LOADMORE : 上拉加载更多
  private static int CURRENT_REFRESH_STATE = SwipeLayout.STATE_REFRESH;

  //     当前页数
  private static int CURRENT_LOAD_PAGE = 1;
  //    搜索关键字
  private static String KEY_WORDS = null;

//  @BindView(R.id.iv_search)
//  ImageButton ivSearch;

  @BindView(R.id.et_search_content)
  MyEditText etSearchContent;

  @BindView(R.id.swipe_target)
  ListView lvCarArchive;

  @BindView(R.id.swipe_layout)
  SwipeLayout swipeLayout;

  @BindView(R.id.tv_search_content)
  TextView tvSearchContent;

  @BindView(R.id.ll_empty_content_display)
  LinearLayout llEmptyContentDisplay;

  private CarArchiveAdapter adapter;
  private ArrayList<CarArchive> dataList;

  private Handler uiRefreshHandler =
      new Handler() {

        @Override
        public void handleMessage(Message msg) {

          switch (msg.what) {
            case SwipeLayout.STATE_NORMAL:
              if (CURRENT_REFRESH_STATE == SwipeLayout.STATE_REFRESH) {
                onRefreshSuccessed((ArrayList<CarArchive>) msg.obj);
              } else {
                onLoadMoreSuccessed((ArrayList<CarArchive>) msg.obj);
              }
              break;
            case SwipeLayout.STATE_SEARCH_BY_KEYWORD:
              if (CURRENT_REFRESH_STATE == SwipeLayout.STATE_REFRESH) {
                onRefreshSuccessed((ArrayList<CarArchive>) msg.obj);
              } else {
                onLoadMoreSuccessed((ArrayList<CarArchive>) msg.obj);
              }
              break;
            default:
              break;
          }
        }
      };

  /**
   * 上拉加载成功刷新
   *
   * @param newList
   */
  private void onLoadMoreSuccessed(ArrayList<CarArchive> newList) {
    if (newList != null) {
      if (newList.size() != 0) {
        swipeLayout.endLoadMore();
        dataList.addAll(newList);
        adapter.notifyDataSetChanged();
        CURRENT_LOAD_PAGE++;
      } else {
        swipeLayout.endLoadMore();
        swipeLayout.setLoadMoreEnabled(false);
      }
    }
  }

  private void onRefreshSuccessed(ArrayList<CarArchive> newList) {
    if (newList != null && newList.size() != 0) {
      hideEmptyView();
      dataList.clear();
      dataList.addAll(newList);
      adapter.notifyDataSetChanged();
      CURRENT_LOAD_PAGE++;
    } else if (newList.size() == 0) {
      showContentEmptyView();
      dataList.clear();
      adapter.notifyDataSetChanged();
    }
    swipeLayout.endRefresh();
  }

  @Override
  protected void doInflaterView(LayoutInflater inflater, ViewGroup container) {
    contentView = inflater.inflate(R.layout.er_frag_car_archive, container, false);
    ButterKnife.bind(this, contentView);
  }

  @Override
  protected void init() {
    KEY_WORDS = "";
    dataList = new ArrayList<>();
    adapter = new CarArchiveAdapter(dataList, getActivity());
    lvCarArchive.setAdapter(adapter);
  }

  @Override
  protected void initView() {
    swipeLayout.setOnRefreshListener(this);
    swipeLayout.setOnLoadMoreListener(this);
//    ivSearch.setOnClickListener(this);
    etSearchContent.addTextChangedListener(this);
    lvCarArchive.setOnItemClickListener(this);

    etSearchContent.setOnEditorActionListener(new TextView.OnEditorActionListener() {
      @Override
      public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_UNSPECIFIED) {
          KEY_WORDS = etSearchContent.getText().toString().trim();
          onRefresh();
          return true;
        } else {
          return false;
        }
      }
    });
  }

  @Override
  protected void initData() {}

  @Override
  public void onResume() {
    super.onResume();
    onRefresh();
    swipeLayout.setRefreshing(true);
  }

  @Override
  public void onClick(View v) {
    switch (v.getId()) {
//      case R.id.iv_search:
//        KEY_WORDS = etSearchContent.getText().toString().trim();
//        //                swipeLayout.setRefreshing(true);
//        onRefresh();
//
//        break;

      default:
        break;
    }
  }

  @Override
  public void onRefresh() {

    CURRENT_REFRESH_STATE = SwipeLayout.STATE_REFRESH;
    CURRENT_LOAD_PAGE = 1;
    loadCarArchiveList(CURRENT_LOAD_PAGE, COUNTS_PER_PAGE, KEY_WORDS);
    swipeLayout.setLoadMoreEnabled(true);
  }

  @Override
  public void onLoadMore() {
    CURRENT_REFRESH_STATE = SwipeLayout.STATE_LOADMORE;
    loadCarArchiveList(CURRENT_LOAD_PAGE, COUNTS_PER_PAGE, KEY_WORDS);
  }

  private void hideEmptyView() {
    // swipeLayout.setVisibility(View.VISIBLE);
    llEmptyContentDisplay.setVisibility(View.INVISIBLE);
  }

  private void showContentEmptyView() {
    if (!TextUtils.isEmpty(KEY_WORDS)) {
      llEmptyContentDisplay.setVisibility(View.VISIBLE);
      tvSearchContent.setText(KEY_WORDS);
    } else {
      llEmptyContentDisplay.setVisibility(View.INVISIBLE);
    }
  }

  private void loadCarArchiveList(int currentLoadPage, int countsPerPage, final String keyWords) {
    HashMap<String, String> params = new HashMap<>();
    //        params.put("authkey",
    // UserInfoManager.getInstance(MyApplication.getInstance()).getAuthKey());
    //        params.put(ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getYkey(),
    // ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getY7e_e73a691f02a46500201c3998e6a2989d());
    params.put("page", String.valueOf(currentLoadPage));
    params.put("rows", String.valueOf(countsPerPage));
    params.put("channel_id", ChannelInfoUtil.getCurrentChannelInfo().getChannel());
    if (!TextUtils.isEmpty(keyWords)) params.put("keywords", keyWords);

    ApiClient.postForm(
        HttpConstants.ARCHIVE_CAR_LIST,
        params,
        new RespCallback<List<CarArchive>>() {

          @Override
          protected void onRequestFailed(String msg) {
            SToast.show(msg);
            if (CURRENT_REFRESH_STATE == SwipeLayout.STATE_REFRESH) {
              swipeLayout.endRefresh();
            } else if (CURRENT_REFRESH_STATE == SwipeLayout.STATE_LOADMORE) {
              swipeLayout.endLoadMore();
            }
          }

          @Override
          protected void onSuccess(List<CarArchive> data) {
            Message msg = uiRefreshHandler.obtainMessage();
            msg.what =
                TextUtils.isEmpty(keyWords)
                    ? SwipeLayout.STATE_NORMAL
                    : SwipeLayout.STATE_SEARCH_BY_KEYWORD;
            msg.obj = data;
            uiRefreshHandler.sendMessage(msg);
          }

          @Override
          public void onError(Exception e) {
            super.onError(e);
            if (CURRENT_REFRESH_STATE == SwipeLayout.STATE_REFRESH) {
              swipeLayout.endRefresh();
            } else if (CURRENT_REFRESH_STATE == SwipeLayout.STATE_LOADMORE) {
              swipeLayout.endLoadMore();
            }
          }
        });
  }

  @Override
  public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

  @Override
  public void onTextChanged(CharSequence s, int start, int before, int count) {}

  @Override
  public void afterTextChanged(Editable s) {
    if (TextUtils.isEmpty(s.toString())) {
      KEY_WORDS = null;
    }
  }

  @Override
  public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    Intent intent = new Intent(CarArchiveFragment.this.getActivity(), AddCarArchiveActivity.class);
    intent.putExtra("CAR_ARCHIVE", dataList.get(position));
    startActivity(intent);
  }

  @Override
  public void onDestroy() {
    super.onDestroy();
    uiRefreshHandler.removeCallbacksAndMessages(null);
  }
}
